/*
 */
;
(function ($) {
    var suggestionRowClass = 'om-suggestion-list-row';
    var suggestionHighLightClass = 'om-state-hover';
    var _valueKey = '_val';

    /**
     * 代码数据通过自动配置来显示
     * 1 根据配置分成2个输入框
     * 2 从JS中获取数据
     * 3 key 和value同时进行选择
     */
    $.omWidget('om.omCode', {
        options:/** @lends omSuggestion#*/{
            codeName:null,

            /**
             * 下拉框的高度（单位是px）。<b>注意：由于浏览器的限制，这个属性的最小值是31，如果小于这个值时将看不到垂直滚动条</b>
             * @type Number
             * @default 300
             */
            listHeight:200,

            /**
             *  下拉框的宽度，如果不定义默认与input框一样宽
             */
            listWidth:false,

            /**
             * 当input框的值为空时，input框里出现提示消息。当input框得到焦点或者input框的值不为空时这个提示消息会自动消失。
             * @name omCombo#emptyText
             * @default 无
             * @type String */
            emptyText:'请输入',

            ronly:false, //增加一个只读状态方法,非disabled
            /**
             * 选择下拉框中一个后触发事件。
             * @event
             * @param text 输入框里当前文本
             * @param rowData 行记录，是Ajax请求返回的数据中的一行
             * @param index 当前行在下拉框所有行中的索引（第一行是0，第二行是1...）
             * @param event jQuery.Event对象
             * @example
             * $('#inputID').omSuggestion({
             *         onSelect:function(rowData,text,index,event){
             *                 $('#searchbut').click(); //选择完后自动点击“查询”按钮
             *         }
             * });
             */
            onSelect:function (rowData, text, index, event) {/*do nothing*/
            }
        },
        _create:function () {
//            if (typeof eval(this.options.codeName) === 'undefined') {
//                alert('未引入[' + this.options.codeName + ']JS');
//            }
            //this.element.addClass('om-suggestion om-widget om-state-default om-state-nobg');
            this.dropList = $('<div class="om-widget"><div class="om-widget-content om-droplist"></div></div>').css({position:'absolute', zIndex:2000}).appendTo(document.body).children().first().hide();
        },
        setData:function(combox){
            this.options.codeName = combox;
            var inputEl = this.element;
            //TODO 请输入没有弄进入
            inputEl.val('');
            inputEl.attr(_valueKey, '');
        },
        _init:function () {
            this._refeshEmptyText(false);
            this._bindEvent();
        },

        _bindEvent:function () {
            var self = this,
                inputEl = this.element,
                dropList = this.dropList;
            //绑定按键事件
            inputEl.focus(function () {
                //$(this).addClass("om-state-focus");
                self._refeshEmptyText(true);
                inputEl.select();
            }).blur(function () {
                    //检查输入值是否在JSON数组内,否则置为空
                    var text = inputEl.val();
                    if (text !== '') {
                        var records = $.data(inputEl, 'records');
                        if (records == undefined) {
                            return;
                        }
                        var isInkeys = false;
                        for (var i = 0; i < records.length; i++) {
                            if (records[i].text == text) {
                                isInkeys = true;
                            }
                        }
                        if (!isInkeys) {//输入值没有在combox key值内
                            inputEl.val('');
                            inputEl.attr(_valueKey, '');
                        }
                        //判断此时值是否已附上
                        if (inputEl.attr(_valueKey) == undefined || inputEl.attr(_valueKey) == '') {//复制进来的值也清空
                            inputEl.val('');
                        }
                    } else {
                        //输入值清空后,将隐藏值也置为空
                        inputEl.attr(_valueKey, '');
                    }
                    self._refeshEmptyText(false);
                }).keydown(function (e) {
                    if (e.keyCode == $.om.keyCode.TAB) {
                        dropList.hide();
                    }
                }).keyup(function (e) {
                    var key = e.keyCode,
                        keyEnum = $.om.keyCode;
                    switch (key) {
                        case keyEnum.DOWN: //down
                            if (dropList.css('display') !== 'none') {
                                self._selectNext();
                            } else {
                                if (dropList.find('.' + suggestionRowClass).size() > 0) {
                                    dropList.show();
                                }
                            }
                            break;
                        case keyEnum.UP: //up
                            if (dropList.css('display') !== 'none') {
                                self._selectPrev();
                            } else {
                                if (dropList.find('.' + suggestionRowClass).size() > 0) {
                                    dropList.show();
                                }
                            }
                            break;
                        case keyEnum.ENTER: //enter
                            if (dropList.css('display') === 'none') {
                                return;
                            }
                            dropList.hide();
                            //trigger onSelect handler
                            self._triggerOnSelect(e);
                            return false;
                        case keyEnum.ESCAPE: //esc
                            dropList.hide();
                            break;
                        case keyEnum.TAB: //tab
                            //only trigger the blur event
                            break;
                        default:
                            self._suggest();
                    }
                }).mousedown(function (e) {
                    e.stopPropagation();
                });

            dropList.mousedown(function (e) {
                e.stopPropagation();
            });

            $(document).bind('mousedown.omSuggestion', this.globalEvent = function () {
                dropList.hide();
            });
        },
        _clear:function () {
            //this.element.val('');
            return this.dropList.find('.' + suggestionRowClass).removeClass(suggestionHighLightClass);
        },
        _focusFirst:function () {
            var dropList = this.dropList,
                all = this._clear();
            //添加高亮样式
            var target = $(all.get(0)).addClass(suggestionHighLightClass);
            //向下滚动
            var targetTop = target.position().top;
            var offset = targetTop + target.outerHeight() - dropList.height();
            if (offset > 0) {
                dropList.scrollTop(dropList.scrollTop() + offset);
            }
        },
        _selectNext:function () {
            var dropList = this.dropList,
                index = dropList.find('.' + suggestionHighLightClass).index(), //查找高亮位
                all = this._clear();
            index += 1;
            if (index >= all.size()) {
                index = 0;
            }
            this._scrollToAndSelect(all, index, dropList);
        },
        _selectPrev:function () {
            var dropList = this.dropList,
                index = dropList.find('.' + suggestionHighLightClass).index(),
                all = this._clear();
            index -= 1;
            if (index < 0) {
                index = all.size() - 1;
            }
            this._scrollToAndSelect(all, index, dropList);
        },
        _scrollToAndSelect:function (all, index, dropList) {
            if (all.size() < 1) {
                return;
            }
            var target = $(all.get(index)).addClass(suggestionHighLightClass);
            var targetTop = target.position().top;
            if (targetTop <= 0) {
                //需要向上滚动滚动条
                dropList.scrollTop(dropList.scrollTop() + targetTop);
            } else {
                //需要向下滚动滚动条
                var offset = targetTop + target.outerHeight() - dropList.height();
                if (offset > 0) {
                    dropList.scrollTop(dropList.scrollTop() + offset);
                }
            }
            //this._select(index);
        },

        /*选择一条数据置入input中*/
        _select:function (index) {
            var inputEl = this.element;
            var records = $.data(inputEl, 'records');
            var rowData = records[index];
            inputEl.val(rowData.text);
            inputEl.attr(_valueKey, rowData.value);
            //this._refeshEmptyText(this.options.emptyText);
        },

        /*过滤处理*/
        _suggest:function () {
            var inputEl = this.element;
            var inputText = inputEl.val();
            var options = this.options;
            var data = [];//本次显示的列表内容
            if (inputText.length > 0) {
                //过滤,创建列表 TODO 代码采用首字母匹配,文本采用模糊匹配
                var dataSource = eval(options.codeName);
                //var regExp = new RegExp("^" + text, "ig");
                $(dataSource).each(function () {
                    var srctext = this.text.toUpperCase();
                    //var srcvalue = this.value.toUpperCase();
                    /*
                    * 其实应该判断这个 value值,但目前value值中也含代码，如果在text中强行判断是否包含，
                    * 当输入代码时也造成了模糊匹配，不能首字母匹配代码
                    * */
                    if (srctext.indexOf(inputText.toUpperCase()) === 0) {
                        data.push(this);
                    } else {
                        var textAry = srctext.split(" ");//特殊处理了,没办法,前期没规范好
                        if (textAry.length>1) {
                            if (textAry[1].indexOf(inputText.toUpperCase()) != -1) {
                                data.push(this);
                            }
                        }
                    }
                });

                $.data(inputEl, 'records', data);//将本次查询结果列表保存起来,供选则时使用
                this._buildDropList(data, inputText);
            } else {
                this.dropList.empty().hide();
            }
        },

        /**
         * 创建列表内容
         * @param records list[map]
         * @param text
         * @private
         */
        _buildDropList:function (records, text) {
            var inputEl = this.element;
            var dropList = this.dropList.empty().css('height', 'auto');
            var self = this;//当前omCode对象
            $(records).each(function (index) {
                self._addRow(this.text, dropList);
            });

            var all = dropList.find('.' + suggestionRowClass);
            if (all.size() > 0) {
                dropList.parent().css('left', parseInt(inputEl.offset().left)).css('top', inputEl.offset().top + inputEl.outerHeight());
                var listWidth = this.options.listWidth;
                if (!listWidth) {//没有定义
                    dropList.parent().width(inputEl.outerWidth());
                } else if (listWidth !== 'auto') {
                    dropList.parent().width(listWidth);
                }
                all.mouseover(function () {
                    all.removeClass(suggestionHighLightClass);
                    $(this).addClass(suggestionHighLightClass);
                }).mousedown(function (event) {
                        var index = dropList.find('.' + suggestionHighLightClass).index();
                        self._select(index);
                        dropList.hide();
                        //trigger onSelect handler
                        self._triggerOnSelect(event);
                    });
                dropList.show();//显示列表
                this._focusFirst();//让选择框选中列表中第一个值,方便直接回车

                var listMaxHeight = this.options.listHeight;
                if (listMaxHeight !== 'auto') {
                    if (dropList.height() > listMaxHeight) {
                        dropList.height(listMaxHeight).css('overflow', 'auto');
                    }
                }
                dropList.scrollTop(0);
            }
        },
        _addRow:function (html, dropList) {
            $('<div class="' + suggestionRowClass + '">' + html + '</div>').appendTo(dropList);
        },
        _triggerOnSelect:function (event) {
            var onSelect = this.options.onSelect;
            if (onSelect) {
                var index = this.dropList.find('.' + suggestionHighLightClass).index();
                if (index < 0) {
                    return;
                }
                //从当前构建的droplist中数据,获取选中的行
                var records = $.data(this.element, 'records'),
                    rowData = records[index],
                    text = rowData.text;
                //这里直接赋值
                this._select(index);
                this._trigger("onSelect", event, rowData, text, index);
            }
        },
        _refeshEmptyText:function (isfocus) {
            var inputEl = this.element;
            var emptyText = this.options.emptyText;

            if (!emptyText)
                return;

            //如果初始赋值,则不是emptyText;修改为通过_val判断
            if (this._isEmpty(inputEl.attr(_valueKey))) {
                if (inputEl.val() === '') {
                    inputEl.val(emptyText).addClass('om-empty-text');
                } else if (inputEl.val() === emptyText) {
                    if (isfocus) {
                        inputEl.val('');
                        inputEl.removeClass('om-empty-text');
                    } else {
                        inputEl.addClass('om-empty-text');
                    }
                }
            } else {
                inputEl.removeClass('om-empty-text');
            }
//            if (inputEl.val() === '') {
//                inputEl.val(emptyText).addClass('om-empty-text');
//            } else {
//                if(inputEl.val() === emptyText){
//                    inputEl.val('');
//                }
//                inputEl.removeClass('om-empty-text');
//            }
        },
        /**
         * 将组件置为只读
         */
        ronly:function (isR) {
            if (isR) {//设置只读
                var input = this.element;
                //distroy event listening
                input.attr('readonly', 'readonly').addClass('om_readonly').unbind();
                //this.options.disabled = true;
                //this.expandTrigger.addClass('om-state-disabled').unbind();
            } else {//取消只读
                var input = this.element;
                input.removeAttr('readonly').removeClass('om_readonly').unbind();
                //this.options.disabled = false;
                // this.expandTrigger.removeClass('om-state-disabled').unbind();
                //rebuild event listening
                this._bindEvent();
            }
        },
        /*
         * 获取列表数据
         * */
        getData:function () {
            var returnValue = $.data(this.element, 'records');
            return returnValue || null;
        },

        _isEmpty:function (v) {
            return v === null || v === undefined || v === '';
        },

        value:function (v) {
            if (typeof v === 'undefined') {
                var value = $(this.element).attr(_valueKey);
                return value ? value : '';
            } else {
                var self = this;
                var dataSource = eval(this.options.codeName);
                var inputEl = this.element;
                $(dataSource).each(function () {
                    if (this.value == v) {
                        inputEl.val(this.text);
                        inputEl.attr(_valueKey, this.value);
                        self._refeshEmptyText(false);
                    }
                });
                return this;
            }
        }
    });

})(jQuery);
